include Common.mk

# 用到的目录: 内核目录 + 用户目录
KERN = kernel
USER = user

# qemu需要的信息: 
# 内核编译链接得到的可执行文件 + 用户程序所在的文件系统映像 + 硬件核心数量
KERNEL_ELF = kernel-qemu
KERNEL_BIN = kernel.bin
KERNEL_IMG = kernel.img
FS_IMG = sdcard.img
CPUNUM = 1

.PHONY: clean $(KERN) $(USER)

# 递归 make build
$(KERN):
	$(MAKE) build --directory=$@

$(USER):
	$(MAKE) init --directory=$@


# 默认
all: build

# 生成kernel-qemu
build: $(KERN)
	$(OBJCOPY) -O binary $(KERNEL_ELF) $(KERNEL_BIN)

# QEMU相关配置
QEMU     =  qemu-system-riscv64
QEMUOPTS =  -machine virt -bios default -kernel $(KERNEL_ELF) 
QEMUOPTS += -m 128M -smp $(CPUNUM) -nographic
QEMUOPTS += -drive file=$(FS_IMG),if=none,format=raw,id=x0
QEMUOPTS += -device virtio-blk-device,drive=x0,bus=virtio-mmio-bus.0
QEMUOPTS += -device virtio-net-device,netdev=net -netdev user,id=net

# qemu运行
qemu: $(USER) $(KERN)
	cp sdcard/$(FS_IMG) $(FS_IMG)
	$(QEMU) $(QEMUOPTS)

# 清除
clean: 
	$(MAKE) --directory=$(KERN) clean
	$(MAKE) --directory=$(USER) clean
	rm -f $(KERNEL_ELF) $(FS_IMG) $(KERNEL_BIN) $(KERNEL_IMG) .gdbinit

# 调试
GDBPORT = $(shell expr `id -u` % 5000 + 25000)
QEMUGDB = $(shell if $(QEMU) -help | grep -q '^-gdb'; \
	then echo "-gdb tcp::$(GDBPORT)"; \
	else echo "-s -p $(GDBPORT)"; fi)

.gdbinit: .gdbinit.tmpl-riscv
	sed "s/:1234/:$(GDBPORT)/" < $^ > $@

qemu-gdb: $(USER) $(KERN) .gdbinit
	cp sdcard/$(FS_IMG) $(FS_IMG)
	$(QEMU) $(QEMUOPTS) -S $(QEMUGDB)

mkimage:
		mkimage -A riscv -O linux -C none -T kernel -a 0x40200000 -e 0x40200000 \
		-n toyos -d $(KERNEL_BIN) $(KERNEL_IMG)